from flask import Blueprint, jsonify, request
import json
from loguru import logger
from app.err_no import errno_no
import traceback
from app.db import dbOrderQuery

blueprint = Blueprint('order_query', __name__, url_prefix='/api/order')

@blueprint.route('/v1/query', methods=['POST'])
def query():
    try:
        j_data = json.loads(request.data)
        startTime = j_data.get('start_time')
        endTime = j_data.get('end_time')
        deviceNo = j_data.get('device_no')
        stallNo = j_data.get('stallNo')
        billState = j_data.get('bill_state')
        payType = j_data.get('pay_type')
        startPage = j_data.get('startPage')
        pageSize = j_data.get('pageSize')
        if startTime is None or len(startTime) <= 0 \
            or endTime is None or len(endTime) <= 0 \
            or deviceNo is None or len(deviceNo) <= 0 \
            or stallNo is None or len(stallNo) <= 0 \
            or billState is None or isinstance(billState, int) is False \
            or payType is None or isinstance(payType, int) is False \
            or startPage is None or isinstance(startPage, int) is False \
            or pageSize is None or isinstance(pageSize, int) is False :
            return jsonify(errno_no.ErrServerParam.data(None))
            
        data = dbOrderQuery.query(startTime, endTime, stallNo, deviceNo, billState, payType, startPage, pageSize)
        
        return jsonify(errno_no.OK.data(data))
    except Exception as e:
        logger.error(f'errMsg:{str(e)},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))

@blueprint.route('/v1/query_details', methods=['POST'])
def query_details():
    try:
        j_data = json.loads(request.data)
        deviceNo = j_data.get('device_no')
        thirdOrderNo = j_data.get('thirdOrderNo')
        if thirdOrderNo is None or len(thirdOrderNo) <= 0:
            return jsonify(errno_no.ErrServerParam.data(None))
            
        data = dbOrderQuery.query_details(thirdOrderNo, deviceNo)
        return jsonify(errno_no.OK.data(data))
    except Exception as e:
        logger.error(f'errMsg:{str(e)},traceback={traceback.format_exc()}')
        return jsonify(errno_no.ErrServerRuntime.data(None))